import Taro, { Component } from '@tarojs/taro';
import { Button, View, Form, Input, Label } from '@doctorwork/components';
import { connect } from '@tarojs/redux';
import Navigate from '../../components/Navigate/index';
import { rewriteAddMTA } from './../../model/utils/rewrite';
import './index.styl';

const appId = process.env.appId;

@connect(({ auth_h5, loading }) => ({
    ...auth_h5,
    isLoad: loading.effects['auth_h5/getauthList'],
    isLoadMore: loading.effects['auth_h5/loadMore']
}))
@rewriteAddMTA
export default class Index extends Component {
    config = {
        navigationBarTitleText: ''
    };
    constructor(props) {
        super(props);
        this.state = {
            canGetCode: true,
            timeRemain: 10
        };
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.canGetCode) {
            if (this.timer) {
                clearInterval(this.timer);
            }
            let timeRemain = nextProps.timeRemain;
            let _this = this;
            _this.props.dispatch({
                type: 'auth_h5/save',
                payload: {
                    canGetCode: false
                }
            });
            this.timer = setInterval(function() {
                if (timeRemain > 0) {
                    _this.setState({
                        canGetCode: false,
                        timeRemain
                    });
                    timeRemain--;
                } else {
                    _this.setState({
                        canGetCode: true
                    });
                    _this.props.dispatch({
                        type: 'auth_h5/save',
                        payload: {
                            canGetCode: true,
                            timeRemain: 0
                        }
                    });
                    clearInterval(_this.timer);
                }
            }, 1000);
        }
    }
    componentWillMount() {
        console.log('进行鉴权');

        this.props.dispatch({
            type: 'auth_h5/save',
            payload: {
                router: this.$router.params
            }
        });
        const { token, openId, userId } = this.$router.params;
        // 带有token，直接登录
        if (token) {
            this.props.dispatch({
                type: 'auth_h5/loginSilent'
            });
        }
    }
    componentWillUnmount() {
        this.props.dispatch({
            type: '$error/save',
            payload: {
                authTime: ''
            }
        });
    }
    // 获取验证码
    onGetValicode = async () => {
        const pattern = /^((1[3,4,5,6,7,8,9]))\d{9}$/;
        const { phone } = this.props;
        if (!pattern.test(phone)) {
            this.props.dispatch({
                type: '$error/other',
                payload: { errmsg: '手机号不合法' }
            });
            return false;
        }

        if (this.state.disableGetCode) return;
        this.props.dispatch({
            type: 'save',
            payload: {
                disableGetCode: true
            }
        });
        this.props.dispatch({
            type: 'auth_h5/getValidateCode',
            payload: {
                smsType: 1,
                phone: this.props.phone
            }
        });
    };
    onPhoneInput = e => {
        this.props.dispatch({
            type: 'auth_h5/save',
            payload: { phone: e.detail.value }
        });
    };
    onCodeInput = e => {
        this.props.dispatch({
            type: 'auth_h5/save',
            payload: { valiCode: e.detail.value }
        });
    };
    onRegister = async () => {
        const { phone, valiCode } = this.props;
        // 1. 校验手机号和验证码
        if (!phone) {
            this.props.dispatch({
                type: '$error/other',
                payload: { errmsg: '请输入手机号' }
            });
            return false;
        }
        if (!valiCode) {
            this.props.dispatch({
                type: '$error/other',
                payload: { errmsg: '请输入验证码' }
            });
            return false;
        }
        this.bindPhoneRequest();
    };

    // 带验证码绑定手机号
    bindPhoneRequest = async () => {
        const { phone, valiCode, needBindPhone } = this.props;
        const type = needBindPhone ? 'auth_h5/bindPhone' : 'auth_h5/login';
        this.props.dispatch({
            type,
            payload: { account: phone, verifyCode: valiCode, authType: 2 }
        });
    };

    render() {
        const {
            showBindMode,
            phone,
            valiCode,
            disableGetCode,
            needBindPhone
        } = this.props;
        const { timeRemain, canGetCode } = this.state;
        return (
            <View>
                <Navigate
                    title=' '
                    color='black'
                    backgroundColor='white'
                    backTextColor='black'
                />
                <View className='alert-container'>
                    <View className='alert-content'>
                        <Label className='title'>
                            {needBindPhone ? '绑定手机号' : '手机号登录'}{' '}
                        </Label>
                        <View>
                            <Input
                                type='text'
                                placeholder='输入手机号'
                                maxlength='11'
                                value={phone}
                                onInput={this.onPhoneInput.bind(this)}
                            />
                        </View>
                        <View className='relative'>
                            <Input
                                type='text'
                                placeholder='短信验证码'
                                maxlength='6'
                                value={valiCode}
                                onInput={this.onCodeInput.bind(this)}
                            />
                            {canGetCode ? (
                                <Label
                                    onClick={this.onGetValicode.bind(this)}
                                    disabled={disableGetCode}
                                    data-name='获取验证码'
                                >
                                    获取验证码
                                </Label>
                            ) : (
                                <Label>{timeRemain}秒后重新获取</Label>
                            )}
                        </View>
                        <Button onClick={this.onRegister.bind(this)} data-name='登 录'>
                            {needBindPhone ? '绑 定' : '登 录'}
                        </Button>
                    </View>
                </View>
            </View>
        );
    }
}
